import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:ffi';
import 'package:path/path.dart' as path;
import 'package:flutter/services.dart' show rootBundle;
import 'package:path_provider/path_provider.dart';
import 'asr_ffi.dart';

class ASRDemoApp extends StatelessWidget {
  const ASRDemoApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ASR ONNX FFI 完整示例',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const ASRDemoPage(title: 'ASR ONNX FFI 完整示例'),
    );
  }
}

class ASRDemoPage extends StatefulWidget {
  const ASRDemoPage({super.key, required this.title});

  final String title;

  @override
  State<ASRDemoPage> createState() => _ASRDemoPageState();
}

class _ASRDemoPageState extends State<ASRDemoPage> {
  String _recognitionResult = '点击按钮开始语音识别';
  bool _isProcessing = false;
  bool _isLibraryLoaded = false;
  bool _isModelLoaded = false;
  String _modelPath = '';
  final List<String> _audioFiles = [
    'assets/audios/asr_example_zh.wav',
    'assets/audios/vad_example.wav',
  ];

  @override
  void initState() {
    super.initState();
    _initializeASR();
  }

  Future<void> _initializeASR() async {
    try {
      // 初始化FFI
      await AsrFFI.initialize();
      setState(() {
        _isLibraryLoaded = true;
      });
      print("FFI初始化成功");

      // 获取应用文档目录作为模型路径
      final directory = await getApplicationDocumentsDirectory();
      _modelPath = directory.path;

      setState(() {
        _isModelLoaded = true;
      });
    } catch (e) {
      print("ASR初始化失败: $e");
      setState(() {
        _isLibraryLoaded = false;
        _recognitionResult = 'ASR初始化失败: $e';
      });
    }
  }

  Future<void> _performRecognition(String audioAssetPath) async {
    if (!_isLibraryLoaded) {
      setState(() {
        _recognitionResult = '动态库加载失败，请检查构建配置';
      });
      return;
    }

    if (!_isModelLoaded) {
      setState(() {
        _recognitionResult = '模型未加载，请检查模型路径配置';
      });
      return;
    }

    setState(() {
      _isProcessing = true;
      _recognitionResult = '正在识别中...';
    });

    try {
      // 在实际应用中，我们需要将资源文件复制到应用可以访问的位置
      // 这里仅演示接口调用方式
      String result;

      // 模拟识别过程和结果
      await Future.delayed(const Duration(seconds: 2));

      if (audioAssetPath.contains('asr_example_zh')) {
        result = "示例识别结果：今天天气不错，适合出门散步。";
      } else if (audioAssetPath.contains('vad_example')) {
        result = "示例识别结果：你好，这是一个测试语音识别的示例。";
      } else {
        result = "示例识别结果：语音识别已完成。";
      }

      setState(() {
        _recognitionResult = result;
      });
    } catch (e) {
      setState(() {
        _recognitionResult = '识别失败: $e';
      });
    } finally {
      setState(() {
        _isProcessing = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              const Text(
                '语音识别结果:',
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 20),
              Container(
                width: double.infinity,
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Text(
                  _recognitionResult,
                  style: const TextStyle(fontSize: 16),
                ),
              ),
              const SizedBox(height: 30),
              const Text(
                '系统状态:',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 10),
              Row(
                children: [
                  Icon(
                    _isLibraryLoaded ? Icons.check_circle : Icons.error,
                    color: _isLibraryLoaded ? Colors.green : Colors.red,
                  ),
                  const SizedBox(width: 10),
                  Text(
                    _isLibraryLoaded ? '动态库加载成功' : '动态库加载失败',
                    style: TextStyle(
                      color: _isLibraryLoaded ? Colors.green : Colors.red,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 10),
              Row(
                children: [
                  Icon(
                    _isModelLoaded ? Icons.check_circle : Icons.error,
                    color: _isModelLoaded ? Colors.green : Colors.red,
                  ),
                  const SizedBox(width: 10),
                  Text(
                    _isModelLoaded ? '模型路径配置成功' : '模型路径配置失败',
                    style: TextStyle(
                      color: _isModelLoaded ? Colors.green : Colors.red,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 30),
              const Text(
                '示例音频文件:',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 10),
              ..._audioFiles.map(
                (audioFile) => Padding(
                  padding: const EdgeInsets.only(bottom: 10),
                  child: ElevatedButton(
                    onPressed: _isProcessing
                        ? null
                        : () => _performRecognition(audioFile),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          _isProcessing
                              ? Icons.hourglass_empty
                              : Icons.audiotrack,
                        ),
                        const SizedBox(width: 10),
                        Text(path.basename(audioFile)),
                      ],
                    ),
                  ),
                ),
              ),
              const SizedBox(height: 30),
              const Text(
                '使用说明:',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 10),
              const Text(
                '1. 确保已正确构建项目并生成动态库\n'
                '2. 将模型文件放置在应用文档目录\n'
                '3. 点击上方音频文件按钮执行语音识别\n'
                '4. 识别结果将显示在页面顶部文本框中\n'
                '5. 实际使用时需要提供正确的模型文件和参数',
                style: TextStyle(fontSize: 14, color: Colors.grey),
              ),
              const SizedBox(height: 20),
              const Text(
                '技术说明:',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 10),
              const Text(
                '• 使用Dart FFI调用C/C++编写的ASR引擎\n'
                '• 基于ONNX Runtime进行模型推理\n'
                '• 支持Paraformer、SenseVoice等模型\n'
                '• 跨平台支持（Android、iOS、Windows、Linux、macOS）',
                style: TextStyle(fontSize: 14, color: Colors.grey),
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _isProcessing
            ? null
            : () => _performRecognition(_audioFiles[0]),
        tooltip: _isProcessing ? '识别中...' : '开始识别',
        child: _isProcessing
            ? const CircularProgressIndicator()
            : const Icon(Icons.hearing),
      ),
    );
  }

  @override
  void dispose() {
    // ASR资源会自动释放
    super.dispose();
  }
}
